<?php
/**
 * Created by PhpStorm.
 * User: yajunyu
 * Date: 2018/12/19
 * Time: 18:14
 * 后台权限验证
 */

namespace app\upms;

use app\admin\model\UpmsRole;
use app\admin\model\UpmsUser;
use app\common\utils\ReturnCode;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;

class AdminPermission
{
    //请求是否合理
    private $isPermission = false;

    private $userId;

    private $permissionId;


    /**
     * @param $params
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function run(&$params)
    {
        if ($this->checkIsExist()) {
            if ($this->checkIsLogin()) {
                $this->isPermission = $this->checkIsHave();
            }
        } else {
            $this->isPermission = true;
        }

        if (!$this->isPermission) {
            $result['code'] = ReturnCode::AUTH_ERROR;
            $result['msg'] = '没有权限';
            exit(json_encode($result));
        }
    }

    /**
     * @return bool
     * 检测是否登录
     */
    public function checkIsLogin()
    {
        $token = request()->header('token');
        $userInfo = cache($token);
        if (is_string($userInfo)) {
            $this->userId = (json_decode($userInfo, true))['user_id'];
            return true;
        }
        return false;
    }

    /**
     * @return bool
     * 检测是否加入权限控制
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function checkIsExist()
    {
        $permission = Db::table('upms_permission')->where('uri', request()->pathinfo())->field('permission_id')->find();
        if (!empty($permission)) {
            $this->permissionId = $permission['permission_id'];
            return true;
        }
        return false;
    }

    /**
     * @return bool
     * 检测用户是否有权限
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function checkIsHave()
    {

        if (Db::table('upms_user_permission')->where('user_id', $this->userId)->where('permission_id', $this->permissionId)->select()) {
            return true;
        } else {
            $havedRoles = UpmsUser::get($this->userId)->upmsUserRoles;
            $havedPermissions = [];
            foreach ($havedRoles as $havedRole) {
                $havedPermissions = array_merge($havedPermissions, UpmsRole::get($havedRole['role_id'])->upmsRolePermissions);
            }

            foreach ($havedPermissions as $havedPermission) {
                if ($havedPermission['permission_id'] == $this->permissionId) {
                    return true;
                }
            }
        }
        return false;
    }

}